<?php
/*
 * 车主服务类
 * copy from Company.class.php
 * @package    business
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 508782d788a8efa3944313dcb031a3f1676b02c5 $
 */
defined('IN_IXDCW') or exit('Access Denied');
class Business extends BasicModule {

	const CATID_CAR = 4864;
	const CATID_LIFE = 4855;
	const AREAID_CHINA = 3421;

	private $_tableMember;
	private $_tableBusiness;
	private $_tableBusinessAuth;
	private $_tableBusinessPicture;
	private $_tableBusinessData;
	private $_moduleid;

	function __construct($moduleid = 33) {
		parent::__construct();
		$this->_tableMember          = Table::name(Table::NAME_MEMBER);
		$this->_tableBusiness        = Table::name(Table::NAME_BUSINESS);
		$this->_tableBusinessAuth    = Table::name(Table::NAME_BUSINESS_AUTH);
		$this->_tableBusinessPicture = Table::name(Table::NAME_BUSINESS_PICTURE);
		$this->_tableBusinessData    = Table::name(Table::NAME_BUSINESS_DATA);
		$this->_moduleid             = $moduleid;
	}

	public function check($post){
		if(isset($post['shopname']) &&!$post['shopname']) Prompt::alert('请填写商店名称');
		if(isset($post['catid'])){
			if(!$post['catid']) Prompt::alert('请选择商家分类');
			$cat = Category::module($this->_moduleid, $post['catid']);
			if (!$cat['parentid']) {
				Prompt::alert('请选择详细商家分类!');
			}
		}
		if(!$post['areaid']) Prompt::alert('请选择区域');
		if (!Area::get($post['areaid'], 'parentid')){
			Prompt::alert('请选择详细地区范围!');
		}
		if(!$post['address']) Prompt::alert('请填写地址');
		if(!$post['zuobiao']) Prompt::alert('请标注店铺位置!');
		if(isset($post['thumb'])&& !$post['thumb']) Prompt::alert('请上传形象图片!');

		if(isset($post['business'])&& !$post['business']) Prompt::alert('请填写经营项目');
		if(isset($post['content']) && !$post['content'] ) Prompt::alert('请填写店铺说明!');
		if(isset($post['youhui_zhekou']) && !$post['youhui_zhekou']) Prompt::alert('请输入优惠折扣项目!');
		if(!$post['agree_licence']) Prompt::alert('请同意服务条款!');
		return true;
	}

	public function set($post) {
		global $_username, $DT_IP, $_userid;
		$position = explode(',', $post['zuobiao']);
		$return   = array(
			'shopname'  => $post['shopname'],
			'nickname'  => $post['nickname'],
			'thumb'     => $post['thumb'],
			'catid'     => $post['catid'],
			'areaid'    => $post['areaid'],
			'address'   => $post['address'],
			'tel1'      => $post['tel1'],
			'tel2'      => $post['tel2'],
			'service'   => $post['service'],
			'business'  => $post['business'],
			'carstop'   => $post['carstop'],
			'langitude' => $position[0],
			'latitude'  => $position[1],
			'content'   => $post['content'],
			'youhui_zhekou'   => $post['youhui_zhekou'],
			'youhui_tishi'   => $post['youhui_tishi'],
			'status'    => 2, // 3 passed, 2 等待审核
			'editor'    => $_username,
			'ip'        => $DT_IP,
			'userid'    => $_userid,
		);
		return $return;
	}

	public function get($isMainStore = false) {
		global $_userid;
		$mainStore = $isMainStore ? 1 : 0;
		$sqlSelect = "
			select business.* , data.content
			from $this->_tableBusiness business, $this->_tableBusinessData data
			where business.itemid = data.itemid and business.userid=$_userid and business.mainstore = $mainStore";
		return $this->_db->getOne($sqlSelect);
	}

	public function getStore($itemid) {
		$sql = "select * from $this->_tableBusiness where itemid=$itemid";
		return $this->_db->getOne($sql);
	}
	public function getPicture($itemid) {
		$sql = "select * from $this->_tableBusinessPicture where itemid=$itemid";
		return $this->_db->getOne($sql);
	}
	public function delete($itemid, $all = true) {
		global $_userid;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->delete($v, $all);
			}
		} else {
			$r             = $this->getStore($itemid);
			if ($all) {
				if ($r['thumb']) PictureUpload::deletePicture($r['thumb'], $_userid);
				$this->_db->query(Sql::delete($this->_tableBusiness, "itemid=$itemid"));
			}
		}
	}

	public function deletePicture($itemid, $all = true) {
		global $_userid;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->deletePicture($v, $all);
			}
		} else {
			$r             = $this->getPicture($itemid);
			if ($all) {
				if ($r['thumb']) PictureUpload::deletePicture($r['thumb'], $_userid);
				$this->_db->query(Sql::delete($this->_tableBusinessPicture, "itemid=$itemid"));
			}
		}
	}

	public function setPicture($post) {
		global $_username, $_userid, $DT_TIME;
		$return   = array(
			'thumb'  => $post['thumb'],
			'userid'  => $_userid,
			'editor'     => $_username,
			'addtime'     => $DT_TIME,
		);
		return $return;
	}

	public function addPicture($post) {
		global $_userid;
		$post = $this->setPicture($post);
		$sql = Sql::insert($this->_tableBusinessPicture, $post);
		ThumbUpload::clearPicture($this->_moduleid . '_thumb', $post['thumb'], '', $_userid);
		ThumbUpload::clearPicture($this->_moduleid . '_license', $post['license'], '', $_userid);
		$this->_db->query($sql);
	}

	/**
	 * 更新执照信息
	 */
	public function updateLicense($licenseUrl){
		global $_userid, $DT_TIME;
		$auth = $this->_db->getOne('select * from '.$this->_tableBusinessAuth.' where userid =' . $_userid);
		if ($auth) {
			$sql = "update ".$this->_tableBusinessAuth." set license_url='{$licenseUrl}', license_addtime = '$DT_TIME' where userid={$_userid}";
			return $this->_db->query($sql);
		} else {
			$item = array(
				'userid'=> $_userid,
				'license_url'=> $licenseUrl,
				'license_addtime'=> $DT_TIME,
			);
			return $this->_db->query(Sql::insert($this->_tableBusinessAuth, $item));
		}
	}


	public function getBranchStores() {
		global $_userid;
		$sqlSelect = "
			select *
			from $this->_tableBusiness
			where userid=$_userid and mainstore = 0";
		return $this->_db->getAll($sqlSelect);
	}

	public function addBranchStore($post) {
		global $DT_TIME, $_userid;
		$post['addtime']   = $DT_TIME;
		unset($post['content']);
		$sqlInsert = Sql::insert($this->_tableBusiness, $post);
		$this->_db->query($sqlInsert);
		ThumbUpload::clearPicture($this->_moduleid . '_thumb', $post['thumb'], '', $_userid);
		ThumbUpload::clearPicture($this->_moduleid . '_license', $post['license'], '', $_userid);
		return true;
	}
	public function editBranchStore($itemid, $post) {
		global $DT_TIME, $_userid;
		$post = $this->set($post);
		$post['edittime']   = $DT_TIME;
		$branchStore = $this->getStore($itemid);
		foreach($branchStore as $k => $v) {
			if (isset($post[$k]) && $post[$k] != $v) {
				$branchStore[$k] = $post[$k];
			}
		}
		$sqlUpdate = Sql::update($this->_tableBusiness, $branchStore, "itemid={$itemid}");
		$this->_db->query($sqlUpdate);
		ThumbUpload::clearPicture($this->_moduleid . '_thumb', $post['thumb'], $branchStore['thumb'], $_userid);
		ThumbUpload::clearPicture($this->_moduleid . '_license', $post['license'], $branchStore['license'], $_userid);
		return true;
	}

	public function add($post, $isMainStore = false) {
		global $DT_TIME, $_userid;
		$post['mainstore'] = $isMainStore ? 1 : 0;
		if ($isMainStore) {
			// check exists
			$one = $this->_db->getOne("select * from $this->_tableBusiness where userid = $_userid and mainstore =1");
			if ($one) {
				$post['edittime']   = $DT_TIME;
				$content = $post['content'];
				unset($post['content']);
				$post['linkurl'] = $this->linkurl($one['itemid']);
				$sqlUpdate = Sql::update($this->_tableBusiness, $post, "itemid={$one['itemid']}");
				$this->_db->query($sqlUpdate);
				$this->addContent($content, $one['itemid']);

				// 更新所有子分类
				$children = $this->_db->getCol("select itemid from $this->_tableBusiness where userid = $_userid and mainstore =0", 'itemid');
				$sql = Sql::update($this->_tableBusiness, 'catid='.$post['catid'], 'itemid in ('.Sql::in($children).')');
				$this->_db->query($sql);
				ThumbUpload::clearPicture($this->_moduleid . '_thumb', $post['thumb'], $one['thumb'], $_userid);
			} else {
				$post['addtime']   = $DT_TIME;
				$content = $post['content'];
				unset($post['content']);
				$sqlInsert = Sql::insert($this->_tableBusiness, $post);
				$this->_db->query($sqlInsert);
				$itemid = $this->_db->insertId();
				$this->updateLinkurl($itemid);
				$this->addContent($content, $itemid);
				ThumbUpload::clearPicture($this->_moduleid . '_thumb', $post['thumb'], array(), $_userid);
				return 'firstEdit';
			}
		} else {
			$post['addtime']   = $DT_TIME;
			$content = $post['content'];
			unset($post['content']);
			$sqlInsert = Sql::insert($this->_tableBusiness, $post);
			$this->_db->query($sqlInsert);
			$itemid = $this->_db->insertId();
			$this->updateLinkurl($itemid);
			$this->addContent($content, $itemid);
			ThumbUpload::clearPicture($this->_moduleid . '_thumb', $post['thumb'], array(), $_userid);
		}
		return true;
	}

	public function linkurl($itemid) {
		return url('shop/show', 'itemid='.$itemid);
	}

	public function updateLinkurl($itemid) {
		$linkUrl = $this->linkurl($itemid);
		$this->_db->query(Sql::update($this->_tableBusiness, array('linkurl'=>$linkUrl), 'itemid='.$itemid));
	}

	public function addContent($content, $id) {
		$sqlReplace = "replace into $this->_tableBusinessData values ($id, '$content')";
		$this->_db->query($sqlReplace);
	}

	public function verifyUserid($userid) {
		global $DT_TIME;
		if (is_array($userid)) {
			array_map(array($this, __FUNCTION__), $userid);
		} else {
			$item = $this->_db->getOne("select * from {$this->_tableBusinessAuth} where userid = $userid");
			if ($item) {
				$item['verify']        = 1;
				$item['verified_time'] = $DT_TIME;
				return $this->_db->query(Sql::update($this->_tableBusinessAuth, $item, "userid = {$userid}"));
			} else {
				$item['userid']        = $userid;
				$item['verify']        = 1;
				$item['complate']      = 0;
				$item['verified_time'] = $DT_TIME;
				return $this->_db->query(Sql::insert($this->_tableBusinessAuth, $item));
			}
		}
		return true;
	}

	public function unverifyUserid($userid) {
		global $DT_TIME;
		if (is_array($userid)) {
			array_map(array($this, __FUNCTION__), $userid);
		} else {
			$item = $this->_db->getOne("select * from {$this->_tableBusinessAuth} where userid = $userid");
			if ($item) {
				$item['verify']          = 0;
				$item['unverified_time'] = $DT_TIME;
				return $this->_db->query(Sql::update($this->_tableBusinessAuth, $item, "userid = {$userid}"));
			} else {
				$item['userid']          = $userid;
				$item['verify']          = 0;
				$item['complate']        = 0;
				$item['unverified_time'] = $DT_TIME;
				return $this->_db->query(Sql::insert($this->_tableBusinessAuth, $item));
			}
		}
		return true;
	}

	public function complateUserid($userid) {

	}

	public function getAuth($userid) {
		$sql = "
			select
				auth.*, member.username
			from
				$this->_tableBusinessAuth auth, $this->_tableMember member
			where
				auth.userid = member.userid
				and
				auth.userid = $userid";
		return $this->_db->getOne($sql);
	}

	public function listPicture(){
		global $_userid;
		$sqlCount = "
			select count(itemid)
			from $this->_tableBusinessPicture
			where userid = $_userid";
		$pictureCount = $this->_db->getVar($sqlCount);
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($pictureCount);
		$sql = "
			select *
			from $this->_tableBusinessPicture
			where userid = $_userid";
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$pictureList = $this->_db->getAll($sql);
		return $pictureList;
	}

	public function allPicture(){
		global $_userid;
		$sql = "
			select *
			from $this->_tableBusinessPicture
			where userid = $_userid";
		$pictureList = $this->_db->getAll($sql);
		return $pictureList;
	}

	public function updatePicture($url, $intro){
		global $_username, $_userid, $DT_TIME;
		$sql = "select itemid from $this->_tableBusinessPicture where thumb = '$url'";
		$itemid = $this->_db->getVar($sql);
		if ($itemid) {
			$sql = Sql::update($this->_tableBusinessPicture, array('thumb'=>$url, 'intro'=>$intro), 'itemid='.$itemid);
		} else {
			$picture   = array(
				'thumb'  => $url,
				'userid'  => $_userid,
				'intro'  => $intro,
				'editor'     => $_username,
				'addtime'     => $DT_TIME,
			);
			$sql = Sql::insert($this->_tableBusinessPicture, $picture);
		}
		return $this->_db->query($sql);
	}

	public function storeList($condition = "status=3") {
		$sqlCount = "
			select count(*)
			from $this->_tableBusiness
			where $condition";
		$num      = $this->_db->getVar($sqlCount);
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "
			select *
			from $this->_tableBusiness
			where $condition ";
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$members = array();
		$result  = $this->_db->query($sql);
		while ($r = $this->_db->fetchArray($result)) {
			$members[] = $r;
		}
		return $members;
	}

	public function verifiedList() {
		$sqlCount = "
			select
				count(auth.itemid)
			from
				$this->_tableBusinessAuth auth, $this->_tableMember member
			where
				auth.userid = member.userid
				and
				auth.verify = 1";
		$num      = $this->_db->getVar($sqlCount);
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "select
				member.userid, member.username, auth.*, member.groupid
			from
				$this->_tableBusinessAuth auth, $this->_tableMember member
			where
				auth.userid = member.userid
				and
				auth.verify = 1";
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$members = array();
		$result  = $this->_db->query($sql);
		while ($r = $this->_db->fetchArray($result)) {
			$members[] = $r;
		}
		return $members;
	}

	/**
	 * 用户名->id
	 * @param $usernames
	 * @return array
	 */
	public function getUseridsByUsernames($usernames) {
		$sql = "select
				member.userid
			from
				$this->_tableMember member
			where
				member.username in (" . Sql::in($usernames) . ")";
		return $this->_db->getCol($sql, 'userid');
	}
}